package application.common.ui;

import java.util.Objects;
import application.common.ui.controller.LoadingController;
import application.common.util.RouteUtil;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class LoadingStage {

	private Stage stage;
	private LoadingController controller;
	private Task<?> work;
	
	private LoadingStage() {
		
	}
	
	
    public static LoadingStage of(Stage parent, Task<?> work, String ad) {
    	LoadingStage ps = new LoadingStage();
        ps.work = Objects.requireNonNull(work);
        ps.initUI(parent, ad);
        return ps;
    }
    
	public void initUI(Stage parent, String message) {
		stage = new Stage();
		stage.initOwner(parent);
		stage.initModality(Modality.WINDOW_MODAL);
		stage.initStyle(StageStyle.UNDECORATED);
		try {
	  		FXMLLoader loader=new FXMLLoader(RouteUtil.class.getResource("/application/common/ui/fxml/LoadingView.fxml"));
	  		controller = new LoadingController(message);
	  	    loader.setController(controller);
	  	    AnchorPane root = loader.load();
	  	    Scene scene =new Scene(root);
		    scene.getStylesheets().add(getClass().getResource("/application/application.css").toExternalForm());
	  	    stage.setScene(scene);
	  	    work.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
				public void handle(WorkerStateEvent event) {
					stage.close();
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    /**
     * 显示
     */
    public void show() {
        new Thread(work).start();
        stage.show();
    }
	
}
